package com.example.springboot.controller;

import com.example.springboot.entity.Note;
import com.example.springboot.entity.Res;
import com.example.springboot.service.Impl.NoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/notes")
public class NoteController {
    @Autowired
    private NoteService noteService;
    private List<Note> notes;


    @GetMapping("/{id}")
    public Res<Note> getNoteById(@PathVariable Integer id) {
        try {
            Note note = noteService.getNoteById(id);
            if (note != null) {
                return new Res<Note>().code(200).msg("查询成功").data(note);
            } else {
                return new Res<Note>().code(404).msg("笔记未找到");
            }
        } catch (Exception e) {
            return new Res<Note>().code(500).msg("服务错误");
        }
    }

    @GetMapping("/user/{userId}")
    public Res<List<Note>> getNotesByUserId(@PathVariable Integer userId,
                                            @RequestParam(defaultValue = "1") Integer pageNum,
                                            @RequestParam(defaultValue = "10") Integer pageSize,
                                            @RequestParam(defaultValue = "0")Integer importance) {
        try {
            System.out.println("userId: " + userId);
            System.out.println("pageNum: " + pageNum);
            System.out.println(importance);
            List<Note> notes = noteService.getNotesByUserId(userId, pageNum, pageSize, importance);
            System.out.println(notes);
            return new Res<List<Note>>().code(200).msg("查询成功").data(notes);
        } catch (Exception e) {
            return new Res<List<Note>>().code(500).msg("服务错误");
        }
    }

    @PostMapping
    public Res<Void> addNote(@RequestBody Note note) {
        try {
            System.out.println(note);
            if (note.getId() == null) {
                noteService.addNote(note);
            } else {
                noteService.updateNote(note);
            }
            return new Res<Void>().code(200).msg("笔记添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Res<Void>().code(500).msg("服务错误");
        }
    }

    @PutMapping
    public Res<Void> updateNote(@RequestBody Note note) {
        try {
            noteService.updateNote(note);
            return new Res<Void>().code(200).msg("笔记更新成功");
        } catch (Exception e) {
            return new Res<Void>().code(500).msg("服务错误");
        }
    }

    @DeleteMapping("/{id}")
    public Res<Void> deleteNoteById(@PathVariable Integer id) {
        try {
            noteService.deleteNoteById(id);
            return new Res<Void>().code(200).msg("笔记删除成功");
        } catch (Exception e) {
            return new Res<Void>().code(500).msg("服务错误");
        }
    }
}